﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Configuration;

namespace 读取web.config配置文件
{
    internal class FxConfigProvider : FileConfigurationProvider
    {
        public FxConfigProvider(FileConfigurationSource source) : base(source)
        {
        }

        public override void Load(Stream stream)
        {
            // 创建一个不区分大小写的哈希表
            Dictionary<string,string> dic = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase);
            // 创建一个读取xml文档的工具类
            XmlDocument xmlDocument = new XmlDocument();
            // 初始化
            xmlDocument.Load(stream);
            // 处理连接字符串数据
            XmlNodeList connStrs = xmlDocument.SelectNodes("/configuration/connectionStrings/add");
            int i = 0;
            foreach(XmlNode node in connStrs.Cast<XmlNode>())
            {
                string name = node.Attributes["name"].Value;
                string connectionString = node.Attributes["connectionString"].Value;
                var providerName = node.Attributes["providerName"];
                if(providerName != null)
                {
                    dic["ConnStrs:" + i + ":providerName"] = providerName.Value;
                }
                // 将数据进行扁平化处理
                dic["ConnStrs:" + i + ":ConnectionString"] = connectionString;
                dic["ConnStrs:" + i + ":name"] = name;
                i++;
            }
            // 处理appSettings中的数据
            connStrs = xmlDocument.SelectNodes("/configuration/appSettings/add");
            foreach (XmlNode node in connStrs.Cast<XmlNode>())
            {
                string key = node.Attributes["key"].Value;
                key = key.Replace(".",":");
                string value = node.Attributes["value"].Value;
                dic["teacher:" + key] = value;
            }
            // 将处理好的哈希表数据放到FileConfigurationProvider的Data数据中
            this.Data = dic;

        }
    }
}
